package application.thread;

import application.ListOption;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.Semaphore;

/**
 *
 * @author Simão
 */
public abstract class ProtocolThread extends Thread {

    protected Socket socket;
    protected ArrayList<byte[]> readerList, writerList;
    protected Semaphore writerSemaphore, readerSemaphore;

    ProtocolThread(Socket socket) {
        this.socket = socket;
        readerList = new ArrayList<>();
        writerList = new ArrayList<>();
        readerSemaphore = new Semaphore(0);
        writerSemaphore = new Semaphore(0);
    }

    ProtocolThread() {
        readerList = new ArrayList<>();
        writerList = new ArrayList<>();
        readerSemaphore = new Semaphore(0);
        writerSemaphore = new Semaphore(0);
    }

    public synchronized byte[] useWriterList(ListOption option, byte[] stream) {
        switch (option) {
            case GET:
                return writerList.get(0);
            case REMOVE:
                return writerList.remove(0);
            case ADD:
                writerList.add(stream);
                writerSemaphore.release();
                return null;
        }
        return null;
    }

    public synchronized byte[] useReaderList(ListOption option, byte[] stream) {
        switch (option) {
            case GET:
                return readerList.get(0);
            case REMOVE:
                return readerList.remove(0);
            case ADD:
                readerList.add(stream);
                readerSemaphore.release();
                return null;
        }
        return null;
    }
}
